package middleware

import (
    "bytes"
    "github.com/zeromicro/go-zero/core/logx"
    "io"
    "net/http"
)

func WithRequestMiddleware(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if r.Method == http.MethodGet {
            // 记录 GET 请求的参数
            logx.WithContext(r.Context()).Infof("Request URL: %s, Method: %s, Params: %v", r.URL.Path, r.Method, r.URL.Query())
        } else if r.Method == http.MethodPost {
            // 读取 POST 请求的参数
            body, err := io.ReadAll(r.Body)
            if err != nil {
                logx.WithContext(r.Context()).Errorf("Failed to read request body: %s", err.Error())
            } else {
                logx.WithContext(r.Context()).Infof("Request URL: %s, Method: %s, Params: %v", r.URL.Path, r.Method, string(body))
                // 将读取的数据重新放入请求体中
                r.Body = io.NopCloser(bytes.NewBuffer(body))
            }
        }
        // 调用下一个处理函数
        next.ServeHTTP(w, r)
    }
}
